<?php

namespace app\admin\server\music;

use app\admin\common;
use app\admin\model\music\MusicModel;
use app\admin\model\user\UserModel;
use app\admin\ServerBase;
use app\admin\validate\music\MusicValidate;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class MusicServer extends ServerBase
{
    protected $model;
    protected $request;
    /**
     * @var mixed
     */
    protected $param;
    /**
     * @var mixed
     */
    protected $validate;

    function __construct( Request $request)
    {
        //$this->checkAuth();
        $this->request=$request;
        $this->param=$request->param();
        $this->model=new MusicModel();
        $this->validate = new MusicValidate();
    }

    function getList(){
        [$page,$limit] = $this->getPage($this->param);
        [$list,$count] = $this->model->getList($this->request,[],'*',$page,$limit);
        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }

    function getDetail(){
        $info = $this->model->getFindById($this->request->param('id'));
        $this->getMessageCode('adminMessage.success.select',2);
        return $info;
    }
    function add(){
        $post = $this->request->post();

        try {
            $this->model->save($post);
            $this->getMessageCode('adminMessage.success.insert',2);
            return true;
        }catch (\Error $error){
            $this->ERROR = $error->getMessage();
            return false;
        }catch (DbException $dbException){
            $this->ERROR = $dbException->getMessage();
            return false;
        }
    }
    function edit(){
        $id = $this->request->param('id',0);
        $post = $this->request->post();
        $post['id'] = $id;
        if(!$this->validate->scene('edit')->check($post)){
            $this->ERROR = $this->validate->getError();
            return false;
        }
        $info  = $this->model->getFindById($id);
        if(empty($info)){
            $this->getMessageCode('adminMessage.error.update',1);
            return false;
        }
        if($info->save($post)){
            $this->getMessageCode('adminMessage.success.update',2);
            return true;
        }else{
            $this->getMessageCode('adminMessage.error.update',1);
            return false;
        }
    }

    function edit_other(){
        $id = $this->request->post('id');
        $this->model->where('id',$id)->save($this->request->post());
        $this->getMessageCode('adminMessage.success.update',2);
        return true;
    }
    function import(){
        if(!request()->file('file')){
            $this->getMessageCode('adminMessage.excel.import.fileTrue',1);
            return false;
        }
        try{
            $res=common::getImportDataFile('public','/');
            $excel_data=common::importData($res['path'],false,1);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息\
            $this->getMessageCode('adminMessage.excel.import.get_data',1);
            $this->ERROR=$this->error.','.$e->getError();
            return false;
        }
        Db::startTrans();
        try {
            $writer_name = array_unique(array_column($excel_data,'B'));
            $writer_ids = UserModel::getIdsByWriterNameKey($writer_name);
            $insert=[];
            $return =[];
            foreach ($excel_data as $key=>$val){
                $return[$key] =[
                    'code'=>1,
                    'msg'=>'成功'
                ];
                if(empty($val['A'])){
                    $return[$key]['code']=-1;
                    $return[$key]['msg']='标题为空';
                    continue;
                }
                if(empty($writer_ids[$val['B']])){
                    $return[$key]['code']=-1;
                    $return[$key]['msg']='创作者不存在';
                    continue;
                }
                if(empty($val['C'])){
                    $return[$key]['code']=-1;
                    $return[$key]['msg']='音乐链接不能为空';
                    continue;
                }
                if(empty($val['E'])){
                    $return[$key]['code']=-1;
                    $return[$key]['msg']='价格不能为空';
                    continue;
                }
                $insert[]=[
                    'title'=>$val['A'],
                    'user_id'=>$writer_ids[$val['B']],
                    'url'=>$val['C'],
                    'img'=>'',
                    'content'=>'',
                    'single_status'=>$val['D']=='是'?1:-1,
                    'price'=>$val['E'],
                    'original_price'=>$val['F']??0,
                    'play_num'=>$val['G']??0,
                    'sale'=>$val['H']??0,
                    'bmp'=>$val['I']??'',
                    'key'=>$val['J']??'',
                    'writer_rate'=>$val['K']??0,
                ];
            }
            if(empty($insert)){
                $this->getMessageCode('adminMessage.error.insert',1);
            }else{
                $this->model->saveAll($insert);
                $this->getMessageCode('adminMessage.success.insert',2);
                Db::commit();
            }
            return $return;
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR=$exception->getMessage();
            return false;
        }
    }
}

